<template>
    <div>
        <div class="operatBtnWrapper">
            <!-- <button class="operatBtn marR5" @click.stop="routerToAdd">新增组织架构</button> -->
            <button class="operatBtn marR5" v-if = "structureList.length > 0" @click.stop="routerToView">组织架构图</button>
		</div>

        <div class="marLR20">
            <el-table :data="formatData" :row-style="showRow"  class="tableWrapper"  border="true" size = "medium" row-class-name = "rowClass">
                <el-table-column v-for="(column, index) in columns" :key="column.value" :label="column.text" :width="column.width"  :align="column.text === '名称' ? 'left' : 'center'">
                    <template slot-scope="scope">
                        <template v-if="index === 0"><span v-for="space in scope.row._level" class="ms-tree-space" :key="space"></span></template>
                        <span class="tree-ctrl" v-if="iconShow(index,scope.row)" @click="toggleExpanded(scope.$index)">
                        <i v-if="!scope.row._expanded" class="el-icon-plus"></i>
                        <i v-else class="el-icon-minus"></i>
                        </span>
                        <template v-if = "column.type === '名称'">
                            <span class="marR15">
                                {{scope.row[column.value] === null ? 0 : scope.row[column.value]}}
                            </span>
                            <span class="toggleShow">
                                <span title = "新增"  class="marR15">
                                    <icon name="add" class="scaleIcon1 flushIcon svgColor" @click.stop.native = "addStruct(scope.row)"></icon>
                                </span>
                                <!-- <span title = "修改"  class="marR15" v-show = "scope.row['label'] !== '信测通信'"> -->
                                <span title = "修改"  class="marR15">
                                    <icon name="change" class="scaleIcon1" title="修改" @click.stop.native = "editStruct(scope.row)" style="cursor:pointer;"></icon>
                                </span>
                                <span title = "删除" v-show = "scope.row['value'] !== 1 && (scope.row.children === undefined || scope.row.children.length <= 0)">
                                    <icon name="del" class="scaleIcon1" title="删除" @click.native.stop="del(scope.row)" style="cursor:pointer;"></icon>
                                </span>
                            </span>
                        </template>
                        <template v-if = "column.type === '人员数量'">
                            {{scope.row[column.usersCount]}}
                        </template>
                    </template>
                    </el-table-column>
                    <slot></slot>
            </el-table>
        </div>

        <!-- 新增 / 编辑组织 弹框 -->
        <el-dialog
            :title="dialogTitle"
            :visible.sync="isDialogShow"
            width="30%"
            :before-close="cancelStruct"
            center>
            <el-form ref="form" :model="form" :rules="rules" class="paddLR20 marT10" :inline="true" label-width="80px">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="名称" prop="name">
                            <el-input v-model.trim="form.name" class="inputTxtWrapper" maxlength="9" ref = "nameInput"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="上级类别" prop="selectedArr" class="inputTxtWrapper">
                            <!-- :disabled = 'form.structId === 1 ? true : false' -->
                            <el-cascader
                                :disabled = "dialogTitle === '修改组织' ? true : false"
                                expand-trigger="hover"
                                :options="treeList"
                                v-model="form.selectedArr"
                                change-on-select>
                            </el-cascader>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancelStruct">取 消</el-button>
                <el-button type="primary" @click="submitStruct">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>



<script>

import http from '@/assets/js/http'
import _g from '@/assets/js/global'
import treeToArray from '@/assets/js/eval'
 import { mapGetters } from 'vuex'

import treeTable from '@/components/Common/TreeTable'

    export default {
        components: { treeTable },  
        name: 'treeTable',
        data(){
            return{
                isDialogShow : false,// 新增或修改组织弹框默认隐藏
                dialogTitle : '',   //..新增或修改组织弹框标题
                treeList : [],//    弹框组织架构列表

                isAdd : false,// false代表为新增，true代表为修改

                form:{
                    name : '',//..组织名称
                    selectedArr : [],//    上级分类
                    structId : null,//..当前组织架构记录id
                },

                currRowData : null,//   当前行记录数据

                rules: {
                name: [
                    { required: true, message: '请输入名称', trigger: 'blur' }
                ],
                // selectedArr: [
                //         { required: true, message: '请选择组织架构', trigger: 'blur' }
                //     ],
                },

                /* 表头 */
                columns: [{
                    text:'名称',
                    value:'label',
                    type:'名称',
                    usersCount : 'users_count',//.未离职人员总数量
                },{
                    text:'人员数量',
                    value:'label',
                    type:'人员数量',
                    usersCount : 'users_count',//.未离职人员总数量
                }],
                structureList : [],//   所有组织架构列表
            }
        },
        created() {
            this.queryInfiniteLevelStructure()
        },
        computed: {
            // 格式化数据源
            formatData: function() {
                let tmp
                if (!Array.isArray(this.structureList)) {
                    tmp = [this.structureList]
                } else {
                     tmp = this.structureList
                }
                
                const func = treeToArray
                const args = Array.concat([tmp])

                return func.apply(null, args)
            }
        },
        methods: {
             /* 递归获取子类id数组 */
            getChildrenIdsArr(children,structId){
                for(let item of children){
                    if(item.value == structId){
                        item['disabled'] = true
                        // children = children.filter((val) => val.value !== structId)
                    }
                    if(item.children !== undefined){
                        this.getChildrenIdsArr(item.children,structId)
                    }
                }
            },
            /* 显示新增组织弹框 */
            addStruct(row){
                // let structureList = JSON.parse(JSON.stringify(this.structureList))
                let structureList = this.structureList
                
                let selectedArr = []//    选中的上级分类

                this.isDialogShow = true
                this.dialogTitle = '新增组织'
                // this.getChildrenIdsArr(structureList,row.value)
                this.treeList = structureList

                if(row.path){//    如果不为最顶层组织
                    selectedArr = row.path.split(',').map(item =>  +item);  
                    this.form.selectedArr = [].concat(selectedArr,[row.value])
                }else{//    如果为最顶层组织
                    this.form.selectedArr = [1]
                }

                this.$nextTick(function(){
                    this.$refs.nameInput.focus()
                })

                // this.isAdd = false
            },

            /* 递归获取子类数组 */
            getChildrenArr(children,structId,childArr){
                for(let item of children){
                    if(item.value == structId){
                        if(item.children !== undefined){
                            childArr = [].concat(item.children)
                            return childArr
                            break
                        }
                    }
                    if(item.children !== undefined){
                        childArr = this.getChildrenArr(item.children,structId,childArr)
                    }
                }
                return childArr
            },

            /* 取消新增(编辑)组织 */
            cancelStruct(){
                this.form.name = ''
                this.form.selectedArr = []
                this.form.structId = null
                this.$refs.form.resetFields()
                this.dialogTitle = ''
                this.treeList = []
                this.currRowData = null
                this.isDialogShow = false
            },

            /* 前端递归新增对应记录 */
            IterationAddMenuChildren(arr,obj,parentId){
                const that = this
                if (arr.length) {
                    for (let i in arr) {
                        if(arr[i].value === parentId){
                            if(arr[i].children ===undefined){
                                that.$set(arr[i], 'children', [])
                                // arr[i]['children'] = []
                            }
                            arr[i]['children'].push(obj)
                            break
                        }else{
                            if (arr[i].children !==undefined && arr[i].children.length) {
                                that.IterationAddMenuChildren(arr[i].children,obj,parentId)
                            } 
                        }
                    }
                }
                return
            },

            /* 前端展开父类菜单 */
            expandParentsMenu(children,selectedArr,currId){
                const that = this
                for (let i in children) {
                    if(selectedArr.indexOf(children[i].value) > -1){
                        that.$set(children[i], '_expanded', true)
                        that.$set(children[i], '_show', true)
                        // 如果有孩子且不为当前新增的那层
                        if (children[i].children !==undefined && children[i].children.length && children[i].value !== currId) {
                            that.expandParentsMenu(children[i].children,selectedArr,currId)
                        }
                    }
                }
                return
            },

            /* 递归获取子类id数组 */
            getChildsIdsArr(children,childIdArr){
                const that = this
                for(let item of children){
                    if(childIdArr.indexOf(item.value) <= -1){
                        childIdArr.push(item.value)
                    }
                    if(item.children !== undefined){
                        that.getChildsIdsArr(item.children,childIdArr)
                    }
                }
                return childIdArr
            },

            /* 递归使得指定的节点不可用 */
            makeNodeDisabled(children,idArr){
                const that = this
                for(let item of children){
                    if(idArr.indexOf(item.value) > -1){
                        item['disabled'] = true
                    }
                    if(item.children !== undefined){
                        that.makeNodeDisabled(item.children,idArr)
                    }
                }
            },


             /* 显示编辑组织弹框 */
            editStruct(row){

                let structureList = [].concat(this.structureList)

                // let idArr = [row.value]//    子类和当前类别id数组
                
                let selectedArr = []//    选中的上级分类
                let currRowData = null//    

                this.isDialogShow = true
                this.dialogTitle = '修改组织'

                // 排除自己和子类类别不可选
                // if(row.children !== undefined){
                //     idArr = [].concat(this.getChildsIdsArr(row.children,idArr))
                // }
                // if(structureList[0].children !== undefined){//  如果顶层有子类
                //     this.makeNodeDisabled(structureList[0].children,idArr)
                // }

                

                this.currRowData = row//   当前行记录数据

                if(row.path){//    如果不为最顶层组织
                    selectedArr = row.path.split(',').map(item =>  +item);  
                    // this.form.selectedArr = [].concat(selectedArr)
                }

                this.treeList = structureList
                this.form.selectedArr = [].concat(selectedArr)
                this.form.structId = row.value
                this.form.name = row.label

                // this.isAdd = true
            },
            /* 递归获取子类id和设置path数组 */
            getChildrenIdsPathArr(children,childIdPathArr,strPath){
                const that = this
                for(let item of children){
                    let arr = strPath.split(',').map(val => +val)
                    if(arr.indexOf(item.parent_id) <= -1){
                        strPath = strPath + ',' + item.parent_id
                    }
                    this.$set(item, 'path', strPath)
                    childIdPathArr.push([item.value,strPath])
                    if(item.children !== undefined){
                        childIdPathArr.concat(that.getChildrenIdsPathArr(item.children,childIdPathArr,strPath))
                    }
                }
                return childIdPathArr
            },
            /* 确认新增(编辑)组织 */
            submitStruct(){
                const that = this

                let name = ''//..组织架构名字
                let id = ''//..所属组织架构id

                let structId = null// ..当前组织架构记录id
                let dialogTitle = that.dialogTitle// ..弹框标题

                let currRowData = this.currRowData//    当前行组织记录数据

                let strPath = ''
                let strPathArr = []//   上层路径id数组集合
                let currRowChildIdArr = [structId]//   当前组织和其子类id数组集合

                let index = 0;

                let childArr = []// 上级组织children

                let childIdPathArr = []//   子类id、路径数组，格式[[子类id,子类path],[子类id,子类path]]

                let structureList = that.structureList

                let currObj = null//    当前新增的组织架构信息

                const selectedArr = that.form.selectedArr

                that.$refs.form.validate((valid) => {                                              //  表单校验成功
                    if (valid) {
                        name = that.form.name

                        if(dialogTitle === '新增组织'){
                            structId = that.form.structId
                            index = selectedArr.length - 1
                            id = selectedArr[index]
                            strPath = selectedArr.join(',')

                            // 同一组织下的名称重复性判断
                            childArr = that.getChildrenArr(structureList,id,childArr)

                            for(let item of childArr){
                                if(item.label === name){
                                    _g.toastMsg('warning','同一组织下的名称不允许重复!')
                                    return
                                }
                            }

                            that.$confirm('是否确认新增?', '提示', {
                                confirmButtonText: '确定',
                                cancelButtonText: '取消',
                                type: 'warning',
                                center: true
                            }).then(() => {
                                _g.showLoading('提交中')
                                that.apiPost('admin/infiniteLevelStructure/add', {id,name,strPath}).then((res) => {
                                        _g.showLoading().close()
                                        if(typeof res === 'string'){
                                        res = JSON.parse(res)
                                        }
                                    if (res.code != 200) {
                                        that.handleError(res)
                                    } else {
                                        if(res.data.isSuccess === 0){             //  成功
                                            _g.toastMsg("success", res.message)

                                            // 更新前端数据
                                            currObj = {
                                                label:name,
                                                parent_id:id,
                                                path:strPath,
                                                users_count:0,
                                                value:+res.data.value,
                                                _expanded:undefined,
                                                _show:true
                                            }

                                            that.IterationAddMenuChildren(structureList,currObj,id)//   新增一个组织架构
                                            that.structureList = structureList

                                            // 当前组织的父类菜单一并展开
                                            that.expandParentsMenu(structureList,selectedArr,+res.data.value)

                                            // 关闭弹框
                                            that.cancelStruct()


                                        }else if(res.data.isSuccess === 1){
                                            _g.toastMsg("error", res.message)
                                        }else if(res.data.isSuccess === 2){
                                            _g.toastMsg("warning", res.message)
                                            that.cancelStruct()
                                        }
                                    }
                                })
                            }).catch(() => {})
                        }else if(dialogTitle === '修改组织'){
                            structId = currRowData.value
                            id = currRowData.parent_id
                            // // 如果当前修改的记录不是最顶层且有孩子
                            // if(currRowData.value !== 1 && currRowData.children !== undefined && currRowData.children.length > 0){
                            //     childIdPathArr = that.getChildrenIdsPathArr(currRowData.children,childIdPathArr,strPath)
                            // }

                            // for(let item of childIdPathArr){
                            //     currRowChildIdArr.push(item[0])
                            // }

                            // strPathArr = strPath.split(',').map(val => +val)

                            // //  如果上级父类数组中含当前组织和其子类
                            // if(currRowChildIdArr.filter(item=>strPathArr.indexOf(item)>-1).length > 0){
                            //     _g.toastMsg('warning','上级组织不能是本身及其子类!')
                            //     return
                            // }

                            that.$confirm('是否确认修改?', '提示', {
                                confirmButtonText: '确定',
                                cancelButtonText: '取消',
                                type: 'warning',
                                center: true
                            }).then(() => {
                                _g.showLoading('提交中')
                                // that.apiPost('admin/infiniteLevelStructure/edit', {id,name,strPath,structId,childIdPathArr}).then((res) => {
                                that.apiPost('admin/infiniteLevelStructure/edit', {id,name,structId}).then((res) => {
                                        _g.showLoading().close()
                                        if(typeof res === 'string'){
                                        res = JSON.parse(res)
                                        }
                                    if (res.code != 200) {
                                        that.handleError(res)
                                    } else {
                                        if(res.data.isSuccess === 0){             //  成功
                                            _g.toastMsg("success", res.message)


                                            // 关闭弹框
                                            that.cancelStruct()
                                            that.queryInfiniteLevelStructure(selectedArr,structId)//    重新获取数据

                                        }else if(res.data.isSuccess === 1){
                                            _g.toastMsg("error", res.message)
                                        }else if(res.data.isSuccess === 2){
                                            _g.toastMsg("warning", res.message)
                                            that.cancelStruct()
                                        }
                                    }
                                })
                            }).catch(() => {})
                        }
                    }
                })
            },

            /* 查询无限级组织架构 */
            queryInfiniteLevelStructure(selectedArr,structId){
                const that = this



                _g.showLoading('加载中');
                that.apiPost("admin/infiniteLevelStructure/queryInfiniteLevelStructure").then(res => {
                        _g.showLoading().close()
                        if(typeof res === 'string'){
                            res = JSON.parse(res)
                        }
                        if (res.code != 200) {
                            that.handleError(res)
                        } else if(res.data.isSuccess === 0){
                            that.structureList = res.data.result

                            // 当前组织的父类菜单一并展开
                            if(selectedArr !== undefined && structId !== undefined){
                                if(selectedArr.length > 0 && structId){
                                    that.expandParentsMenu(that.structureList,selectedArr,structId)
                                }
                            }

                        }else if(res.data.isSuccess === 1){
                            _g.toastMsg("error", res.message)
                        }
                })
            },
            //  /* 跳转到新增组织架构页面 */
            // routerToAdd(){
            //     this.$router.push('/admin/structures/addDepart')
            // },
             /* 跳转到组织架构图页面 */
            routerToView(){
                this.$router.push('/admin/structures/viewStructure')
            },

            /* 前端递归删除对应记录 */
            IterationDelateMenuChildren(arr,value){
                const that = this
                if (arr.length) {
                    for (let i in arr) {
                        if (arr[i].children !==undefined && arr[i].children.length) {
                            that.IterationDelateMenuChildren(arr[i].children,value)
                        } else if(arr[i].value === value){
                            arr.splice(i,1)
                            break
                        }
                    }
                }
                return arr
            },

            /* 前端递归修改对应记录 */
            IterationEditMenuChildren(arr,value){

            },

            /* 删除对应记录 */
            del(row){
                const that = this
                let structureList = that.structureList
                const len = structureList.length
                const structId = row.value

                that.$confirm('是否确认删除?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                        center: true
                    }).then(() => {
                            _g.showLoading('删除中')
                            that.apiPost('admin/infiniteLevelStructure/delete', {structId}).then((res) => {
                                _g.showLoading().close()
                                if(typeof res === 'string'){
                                    res = JSON.parse(res)
                                }
                                if (res.code != 200) {
                                    that.handleError(res)
                                } else {
                                    if(res.data.isSuccess === 0){
                                        _g.toastMsg("success", res.message)
                                        
                                         // 递归删除
                                        that.structureList = that.IterationDelateMenuChildren(structureList,structId)

                                    }else if(res.data.isSuccess === 1){
                                        _g.toastMsg("error", res.message)
                                    }else if(res.data.isSuccess === 2){
                                        _g.toastMsg("warning", res.message)
                                    }
                                }
                        })
                    }).catch(() => {})
            },

            /* 递归获取父类id */
            getParentId(oldParent,arr){
                let parentId = oldParent.parent_id
                if(oldParent.parent_id === 0){//   如果为顶层
                     arr.unshift(parentId)
                    return arr
                }else{
                    arr.unshift(parentId)
                    parentId = this.getParentId(oldParent.parent,arr)
                }
                return parentId
            },

            /* 跳转到编辑页面 */
            // routerToEditPage(row){
            //     const name = row.label
            //     const structId = row.value

            //     let arr = []
            //     let structIdsStr = ''
            //     arr = this.getParentId(row,arr)
            //     structIdsStr = arr.join(',')
            //     this.$router.push({path : '/admin/structures/editDepart',query:{structIdsStr,name,structId}})
            // },

            showRow: function(row) {
                const show = (row.row.parent ? (row.row.parent._expanded && row.row.parent._show) : true)
                row.row._show = show
                return show ? 'animation:treeTableShow 1s;-webkit-animation:treeTableShow 1s;' : 'display:none;'
            },
            // 切换下级是否展开
            toggleExpanded: function(trIndex) {
                const record = this.formatData[trIndex]
                record._expanded = !record._expanded
            },
            // 图标显示
            iconShow(index, record) {
                return (index === 0 && record.children && record.children.length > 0)
            }
        },
        mixins: [http]
    }
</script>
<style rel="stylesheet/css">
  @keyframes treeTableShow {
    from {opacity: 0;}
    to {opacity: 1;}
  }
  @-webkit-keyframes treeTableShow {
    from {opacity: 0;}
    to {opacity: 1;}
  }
</style>

<style lang="scss" rel="stylesheet/scss" scoped>
  $color-blue: #2196F3;
  $space-width: 18px;
  .ms-tree-space {
    position: relative;
    top: 1px;
    display: inline-block;
    font-style: normal;
    font-weight: 400;
    line-height: 1;
    width: $space-width;
    height: 14px;
    &::before {
      content: ""
    }
  }
  .processContainer{
    width: 100%;
    height: 100%;
  }
  table td {
    line-height: 26px;
  }

  .tree-ctrl{
    position: relative;
    cursor: pointer;
    color: $color-blue;
    margin-left: -$space-width;
  }
</style>